package api

import (
	"gitee.com/go-course/go12/devcloud-mini/cmdb/apps/resource"
	restfulspec "github.com/emicklei/go-restful-openapi/v2"
	"github.com/emicklei/go-restful/v3"
	"github.com/infraboard/mcube/http/label"
	"github.com/infraboard/mcube/http/request"
	"github.com/infraboard/mcube/http/restful/response"
)

func (h *handler) Registry(ws *restful.WebService) {
	tags := []string{"资源管理"}

	ws.Route(ws.GET("/").To(h.Search).
		Doc("资源搜索").
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Metadata(label.Auth, label.Enable).
		Param(ws.PathParameter("keywords", "关键字搜索参数").DataType("string").DefaultValue("")).
		Param(ws.PathParameter("page_size", "页大小").DataType("interger").DefaultValue("20")).
		Param(ws.PathParameter("page_number", "页码").DataType("interger").DefaultValue("1")).
		Returns(200, "OK", resource.ResourceSet{}))
}

func (h *handler) Search(r *restful.Request, w *restful.Response) {
	req := resource.NewSearchRequest()
	req.Keywords = r.QueryParameter("keywords")
	req.Page = request.NewPageRequestFromHTTP(r.Request)

	set, err := h.Svc.Search(r.Request.Context(), req)
	if err != nil {
		response.Failed(w, err)
		return
	}

	response.Success(w, set)
}
